package me.zhangsanfeng.gpss.common.utils;
import me.zhangsanfeng.gpss.common.entity.BaseException;
import me.zhangsanfeng.gpss.common.entity.PageResult;
import me.zhangsanfeng.gpss.common.entity.Result;
import me.zhangsanfeng.gpss.common.enums.HttpCode;
import org.springframework.data.domain.Page;

import java.util.Collection;

/**
 * @ClassName:ResultUtil
 * @Description:接口返回值统一json格式工具类
 * @Author:ZhangYao
 * @Date:2018/11/3 02:04
 * @Version:1.0
 */
public class ResultUtil {

    public static Result success(){
        return success(null);
    }

    public static Result success(Object object){
        Result result = new Result();
        result.setCode(HttpCode.OK.getCode());
        result.setMsg(HttpCode.OK.getMsg());
        if (object instanceof Page){
            if (DataUtil.isNotEmpty(object)){
                Page pageObject = (Page) object;
                PageResult pageResult = new PageResult();
                pageResult.setCode(HttpCode.OK.getCode());
                pageResult.setMsg(HttpCode.OK.getMsg());
                pageResult.setPage(pageObject.getNumber() +1);
                pageResult.setSize(pageObject.getSize());
                pageResult.setPages(pageObject.getTotalPages());
                pageResult.setCount(Integer.valueOf(String.valueOf(pageObject.getTotalElements())));
                pageResult.setData(pageObject.getContent());
                return pageResult;
            }
        }else if (object instanceof Collection){
            Collection collectionObject = (Collection) object;
            result.setCount(collectionObject.size());
        }

        result.setData(object);
        return result;
    }

    public static Result except(Exception e){
        Result result = new Result();
        result.setCode(HttpCode.EX.getCode());
        result.setMsg(HttpCode.EX.getMsg());
        result.setData(e.getMessage());
        return result;
    }

    public static Result error(Exception e){
        Result result = new Result();
        result.setCode(HttpCode.SERVER_ERROR.getCode());
        result.setMsg(HttpCode.SERVER_ERROR.getMsg());
        result.setData(e.getMessage());
        return result;
    }

    public static Result forbidden(String msg){
        return new Result(HttpCode.FORBIDDEN.getCode(),
                HttpCode.FORBIDDEN.getMsg(),msg,0);
    }

    public static Result unauthorized(String msg){
        return new Result(HttpCode.UNAUTHORIZED.getCode(),
                HttpCode.UNAUTHORIZED.getMsg(),msg,0);
    }

    public static Result loginfailure(Exception e){
        return new Result(HttpCode.LOGIN_FAILURE.getCode(),
                HttpCode.LOGIN_FAILURE.getMsg(),e.getMessage(),0);
    }
}
